package com.songlanyun.modules.workPolicy.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.user.controller.AbstractController;
import com.songlanyun.modules.workPolicy.entity.WorkPolicy;
import com.songlanyun.modules.workPolicy.service.WorkPolicyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("/admin/workpolicy")
public class WorkPolicyController extends AbstractController {

    @Autowired
    private WorkPolicyService workPolicyService;


    @GetMapping("/list")
//    @RequiresPermissions("base:workpolicy:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = workPolicyService.queryPage(params);
        return R.ok().put("page", page);

    }


    @GetMapping("/{id}")
//    @RequiresPermissions("base:workpolicy:info")
    public R info(@PathVariable("id") Integer id) {
        WorkPolicy workPolicy = workPolicyService.loadById(id, true);
        return R.ok().put("data", workPolicy);
    }

    /**
     * 新增
     */
    @PostMapping("/add")
//    @RequiresPermissions("base:workpolicy:add")
    public R save(@RequestBody WorkPolicy workPolicy) {
        ValidatorUtils.validateEntity(workPolicy);
        workPolicy.setCreateBy(getUserId());
        workPolicy.setUpdateBy(getUserId());
        WorkPolicy resWorkPolicy = workPolicyService.add(workPolicy);
        return R.ok().put("data", resWorkPolicy);
    }

    /**
     * 修改
     */
    @PutMapping("/update")
//    @RequiresPermissions("base:workpolicy:update")
    public R update(@RequestBody WorkPolicy workPolicy) {
        if (ObjectUtil.isNull(workPolicy.getId())){
            throw new RRException("ID不能为空");
        }
        ValidatorUtils.validateEntity(workPolicy);
        workPolicy.setUpdateBy(getUserId());
        WorkPolicy resWorkPolicy = workPolicyService.update(workPolicy);
        return R.ok().put("data", resWorkPolicy);
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
//    @RequiresPermissions("base:workpolicy:delete")
    public R delete(@PathVariable("id") Integer id) {
        workPolicyService.removeById(id);
        return R.ok();
    }



    /**
     * 获取优先级最高的一条创业政策，有并列的话，按时间倒序
     */
    @GetMapping("/getMinWorkPolicy")
    public R getMinWorkPolicy() {
        WorkPolicy workPolicy = workPolicyService.getOne(new LambdaQueryWrapper<WorkPolicy>()
                .orderByAsc(WorkPolicy::getSort)
                .orderByDesc(WorkPolicy::getCreateTime)
                .last("limit 1"));
        return R.ok().put("data", workPolicy);
    }
}
